package service.impl;

import domain.Task;
import service.NotificationService;
import ui.GUI;
import util.DateComparator;

import java.io.IOException;
import java.util.*;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.logging.FileHandler;
import java.util.logging.Level;
import java.util.logging.XMLFormatter;

/**
 * User: Алексей
 * Date: 13.11.12
 * Time: 19:54
 */
public class NotificationImpl implements NotificationService {

    private List<Task> tasks;
    private GUI gui;
    private static java.util.logging.Logger log = java.util.logging.Logger.getLogger(NotificationImpl.class.getName());

    //параметр погрешности соотношения времени задачи и текущего времени в секундах
    //ВАЖНО!!! 2*eps должно быть > чем startInterval
    private static final int eps = 6;

    //интервал запуска потока нотификатора в секундах
    private static final int startInterval = 10;

    private DateComparator dateComparator = new DateComparator();

    private Task previousTask;

    public NotificationImpl(GUI gui, List<Task> tasks) {
        this.gui = gui;
        this.tasks = tasks;
        try {
            FileHandler fileHandler = new FileHandler("notification.xml");
            fileHandler.setFormatter(new XMLFormatter());
            log.addHandler(fileHandler);
            log.setLevel(Level.ALL);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public Task getNextTask() {
        for (int i = 0; i < tasks.size(); i++)
        if (tasks.get(i) != null && !tasks.get(i).equals(previousTask) && getDelayDate(-eps).compareTo(tasks.get(i).getDate()) <= 0)
            return tasks.get(i);
        return null;
    }

    @Override
    public void waitTaskForExecute() {
        ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
        service.scheduleWithFixedDelay(new Runnable() {

            @Override
            public void run() {
                Task task = getNextTask();
                if (task != null && getDelayDate(eps).compareTo(task.getDate()) >= 0) {
                    gui.makeTaskForExecute(task);
                    previousTask = task;
                    log.fine(String.format("Task %s available for execute", task.getName()));
                }
            }
        }, 0, startInterval, TimeUnit.SECONDS);
    }

    private Date getDelayDate(int delay) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.add(Calendar.SECOND, delay);
        return calendar.getTime();
    }
}
